package com.yzt.zhuju.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.yzt.zhuju.network.entity.sysConfig.AliOSSCredentialBean;

/**
 * 图片上传工具
 */
public class ImageUpLoadUtils {

//    objectKey：上传后的文件名
//
//    uploadFilePath：本地文件（需要上传的文件）路径

    // 域名，一般为"oss-cn-shenzhen.aliyuncs.com"，看你们服务器地址，是杭州就把shenz改成hangzhou
    private static final String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";

    // 存储空间，只你上传到哪个空间里面去（命名规则可查看相关文档）
    private static final String bucketname = "cook-orange";

    // 后台返回的ak，需要在有效期内
    private static String accessKeyId;

    // 后台返回的sk，和ak一暗影，这两个极为重要和危险，安全性相关
    private static String accessKeySecret;

    // 安全性验证的token
    private static String securityToken;

    private static OSSClient oss;

    @SuppressLint("StaticFieldLeak")
    private static ImageUpLoadUtils upLoadImage;

    /**
     * 构建单例 初始化创建图片
     */
    public static ImageUpLoadUtils getInstance() {
        if (null == upLoadImage) {
            synchronized (ImageUpLoadUtils.class) {
                if (upLoadImage == null)
                    upLoadImage = new ImageUpLoadUtils();
            }
        }
        return upLoadImage;
    }

    // 上下文对象
    private Context context;

    /**
     * 初始化上传图片
     */
    public void init(Context context, AliOSSCredentialBean tencentBean) {
        this.context = context;
        accessKeyId = tencentBean.getAccessKeyId();
        accessKeySecret = tencentBean.getAccessKeySecret();
        securityToken = tencentBean.getSecurityToken();

        initOSS();
    }

    public void initOSS() {

        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId,
                accessKeySecret,
                securityToken) {
            @Override
            public OSSFederationToken getFederationToken() {
                //可实现自动获取token
                return super.getFederationToken();
            }
        };
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSSLog.enableLog();
        oss = new OSSClient(context, endpoint, credentialProvider, conf);
    }

    public interface OnAsyncUpLoadListener {

        void onProgress(PutObjectRequest request, long currentSize, long totalSize);

        void onSuccess(PutObjectRequest request, PutObjectResult result, String directory);

        void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException);
    }

    public void asyncUpLoad(final String objectKey, String uploadFilePath, final OnAsyncUpLoadListener onAsyncUpLoadListener) {

        if (!TextUtils.isEmpty(objectKey) && !TextUtils.isEmpty(uploadFilePath) && oss != null) {
            // 构造上传请求
            PutObjectRequest put = new PutObjectRequest(bucketname, "tmpfile/" + objectKey, uploadFilePath);
            // 异步上传时可以设置进度回调
            put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                @Override
                public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                    if (onAsyncUpLoadListener != null) {
                        onAsyncUpLoadListener.onProgress(request, currentSize, totalSize);
                    }
                    Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                }
            });
            oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                    if (onAsyncUpLoadListener != null) {
                        String directory = endpoint.replace("oss-cn", bucketname + ".oss-cn") + "/";
                        onAsyncUpLoadListener.onSuccess(request, result, directory);
                    }
//                    loadDialog.dismiss();
                    Log.d("PutObject", "UploadSuccess");
                    Log.d("ETag", result.getETag());
                    Log.d("RequestId", result.getRequestId());
                }

                @Override
                public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                    if (onAsyncUpLoadListener != null) {
                        onAsyncUpLoadListener.onFailure(request, clientExcepion, serviceException);
                    }
//                    loadDialog.dismiss();
                    // 请求异常
                    if (clientExcepion != null) {
                        // 本地异常如网络异常等
                        clientExcepion.printStackTrace();
                    }
                    if (serviceException != null) {
                        // 服务异常
                        Log.e("ErrorCode", serviceException.getErrorCode());
                        Log.e("RequestId", serviceException.getRequestId());
                        Log.e("HostId", serviceException.getHostId());
                        Log.e("RawMessage", serviceException.getRawMessage());
                    }
                }
            });
        }
    }
}
